from rest_framework import viewsets
from .models import City, DataCenter, Host
from .serializers import CitySerializer, DataCenterSerializer, HostSerializer
from rest_framework.decorators import action
from rest_framework.response import Response
import subprocess


class CityViewSet(viewsets.ModelViewSet):
    queryset = City.objects.all()
    serializer_class = CitySerializer

class DataCenterViewSet(viewsets.ModelViewSet):
    queryset = DataCenter.objects.all()
    serializer_class = DataCenterSerializer

class HostViewSet(viewsets.ModelViewSet):
    queryset = Host.objects.all()
    serializer_class = HostSerializer

    @action(detail=True, methods=['get'])
    def ping(self, request, pk=None):
        host = self.get_object()
        try:
            result = subprocess.run(['ping', '-c', '3', host.ip], 
                                   timeout=5, capture_output=True)
            return Response({'reachable': result.returncode == 0})
        except subprocess.TimeoutExpired:
            return Response({'reachable': False})